// pages/person/coin/saleCoin.js
const httpUtils = require('../../../utils/httpUtils')
const ui = require('../../../utils/ui')

var currentRate = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    coinAmount: 0,
    rate: 0,
    coinCount: 1,
    saleNum: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.requestUserAccount();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  //请求用户账户信息
  requestUserAccount() {
    let obj = {
      method: 'GET',
      url: '/user/' + wx.getStorageSync('USERDATA').platformId + '/coin-convert'
    }
    httpUtils.request(obj).then(res => {
      currentRate = res.data.coinConvertRatio;
      this.setData({
        rate: res.data.coinConvertRatio,
        coinAmount: res.data.balanceCoinAmount
      })
    }).catch(err => {
      console.log('ERROR')
    });
  },
  //监听输入框
  onChange(event) {
    // event.detail 为当前输入的值
    this.setData({
      coinCount: parseInt(event.detail),
      rate: currentRate*parseInt(event.detail)
    })
  },
  //出售金币
  actionSure() {
    console.log(parseInt(this.data.saleNum));
    if (parseInt(this.data.saleNum) <= 0 || this.data.saleNum == '') {
      ui.showToast('出售金币必须大于0');
      return;
    }
    let obj = {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      url: '/user/' + wx.getStorageSync('USERDATA').platformId + '/coin-convert',
      data: {
        coinAmount: this.data.coinCount,
        moneyAmount: this.data.coinCount*currentRate,
        platformId: wx.getStorageSync('USERDATA').platformId
      }
    }
    httpUtils.request(obj).then(res => {
      wx.showToast({
        title: '出售成功',
        icon: 'success',
        duration: 2000,
        mask: true,
        success: function() {
          setTimeout(function() {
            wx.navigateBack({
              delta: 0,
            });
          }, 1500)
        }
      })
      
    }).catch(err => {
      console.log('ERROR')
    });
  }
})